package com.tuanbiao.presenter;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.hzjq.data.entity.BlastDetailEntity;
import com.hzjq.data.entity.BlastEntity;
import com.tuanbiao.base.mvp.BasePresenter;
import com.tuanbiao.controllers.UploadDataController;
import com.tuanbiao.data.callback.OnBaseResultCallback;
import com.tuanbiao.events.UploadDataDetailsEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import timber.log.Timber;

/**
 * @author abiao
 * @since 2022/4/24 16:43
 */
public class UploadDataDetailsPresenter extends BasePresenter<UploadDataController.Model, UploadDataController.DetailsView> implements UploadDataController.DetailsPresenter {
    private BlastEntity mEntity;
    private BlastDetailEntity mBlastDetail;
    private boolean mIsChange;

    public UploadDataDetailsPresenter(UploadDataController.Model model, UploadDataController.DetailsView rootView) {
        super(model, rootView);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void init(UploadDataDetailsEvent event) {
        mEntity = event.getEntity();
        Timber.i("init:" + mEntity);
        EventBus.getDefault().removeStickyEvent(event);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void init() {
        if (null != mEntity) {
            mModel.queryBlastDetailById(mEntity.getBlastId(), entity -> {
                Timber.i(entity.toString());
                mBlastDetail = entity;
                mRootView.showDetails(mEntity);
                mRootView.showDetails(entity);
                mRootView.setItems(entity.getCaps());
            });
        }
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    @Override
    public void startOperateLog() {
        if (null != mBlastDetail) mRootView.startLog(mBlastDetail);
    }

    @Override
    public void update(boolean isUploadAll) {
        mRootView.showLoading();
        mModel.uploadBlast(mEntity,isUploadAll, new OnBaseResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                mIsChange = true;
                if (aBoolean) {
                    mRootView.showMessage("上传成功");
                    mEntity.setUploadStatus(1);
                    mRootView.showDetails(mEntity);
                } else mRootView.showMessage("上传失败，请稍后重试");
            }

            @Override
            public void onFailed(String msg) {
                mRootView.showMessage(msg);
            }

            @Override
            public void onFinish() {
                mRootView.hideLoading();
            }
        });
    }

    @Override
    public int getErrorCount() {
        return mEntity.getErrorCount();
    }

    @Override
    public boolean isChange() {
        return mIsChange;
    }
}
